<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="1500px"
    @close="onClose"
    :close-on-click-modal="false"
  >
    <div class="main">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="" props="time">
          <el-date-picker
            v-model="queryParams.time"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleQuery"
            clearable
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>
        <el-form-item label="套餐名称" prop="comboName">
          <el-input
            style="width: 200px"
            v-model.trim="queryParams.comboName"
            placeholder="请输入套餐名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="state.loading"
        size="default"
        index
        :data="dataList"
        :span-method="objectSpanMethod"
      >
        <el-table-column
          label="日期"
          min-width="100px"
          show-overflow-tooltip
          align="center"
          prop="orderTime"
        />
        <el-table-column
          label="套餐名称"
          min-width="100px"
          show-overflow-tooltip
          align="center"
          prop="comboName"
        />
        <el-table-column label="投放份数" align="center" prop="grantNum" />
        <el-table-column label="已售份数" align="center" prop="saleNum">
          <template #default="{ row }">
            <div :style="`color: ${row.saleNum <= 10 ? 'red' : ''};`">{{ row.saleNum }} </div>
          </template>
        </el-table-column>
        <el-table-column label="小程序已售份数" align="center" prop="appSaleNum" />
        <el-table-column label="设备已售份数" align="center" prop="machineSaleNum" />
        <el-table-column label="已售份数同比" align="center" prop="saleNumRate">
          <template #default="{ row }"> {{ row.saleNumRate || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="已售份数环比" align="center" prop="saleNumLoopRate">
          <template #default="{ row }"> {{ row.saleNumLoopRate || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="已售总金额(元)" align="center" prop="saleMoney">
          <template #default="{ row }">
            <div :style="`color: ${row.saleMoney <= 100 ? 'red' : ''};`">{{ row.saleMoney }} </div>
          </template>
        </el-table-column>
        <el-table-column label="已售总金额同比" align="center" prop="saleMoneyRate">
          <template #default="{ row }"> {{ row.saleMoneyRate || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="已售总金额环比" align="center" prop="saleMoneyLoopRate">
          <template #default="{ row }"> {{ row.saleMoneyLoopRate || '0.00' }}% </template>
        </el-table-column>
        <el-table-column label="餐品售卖率" align="center" prop="comboSaleRate">
          <template #default="{ row }">
            <div :style="`color: ${row.comboSaleRate <= 40 ? 'red' : ''};`"
              >{{ row.comboSaleRate || '0.00' }}%
            </div>
          </template>
        </el-table-column>
        <el-table-column label="未取份数" align="center" prop="notTakeNum" />
        <el-table-column label="餐品未售份数" align="center" prop="notSaleNum" />
        <el-table-column label="退款数" align="center" prop="refundNum" />
        <el-table-column label="日均单价" align="center" prop="unitPrice" />
        <el-table-column label="客单价中位数" align="center" prop="moneyMedian" />
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="state.total > 0"
          :total="state.total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { getcomboSalesDetailListApi } from '@/api/statistic'
const queryRef = ref(null)
const { proxy } = getCurrentInstance()
const emits = defineEmits(['close'])
const dataList = ref([])
const visible = ref(false)
const title = ref('')

const queryParams = reactive({
  comboName: '',
  startTime: '',
  endTime: '',
  positionName: '',
  pageNum: 1,
  pageSize: 10
})
const state = reactive({
  total: 0,
  loading: false,
  timeRange: []
})

/** 查询用户列表 */
async function getList() {
  state.loading = true
  const [startTime, endTime] = queryParams.time || []
  queryParams.startTime = startTime ? startTime : ''
  queryParams.endTime = endTime ? endTime : ''
  const params = {
    ...queryParams
  }
  delete params.time
  try {
    const r = await getcomboSalesDetailListApi(params)
    const list = r?.rows ?? []
    dataList.value = []
    list.forEach((item) => {
      item.saleDataVOS?.forEach((i) => {
        dataList.value.push({
          ...item,
          ...i
        })
      })
    })
    console.log('dataList.value', dataList.value)
    state.total = r?.total ?? 0
  } finally {
    state.loading = false
  }
}
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  const arr = [
    '日期',
    '已售份数同比',
    '已售份数环比',
    '已售总金额同比',
    '已售总金额环比',
    '客单价中位数'
  ]
  if (arr.includes(column.label)) {
    // 获取当前单元格的值
    const currentValue = row.orderTime

    // 获取上一行相同列的值
    const preRow = dataList.value[rowIndex - 1]
    const preValue = preRow ? preRow.orderTime : null

    // 如果当前时间值和上一行的值相同，则将当前单元格隐藏
    if (currentValue === preValue) {
      return {
        rowspan: 0,
        colspan: 0
      }
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1
      for (let i = rowIndex + 1; i < dataList.value.length; i++) {
        const nextRow = dataList.value[i]
        const nextValue = nextRow.orderTime
        if (nextValue === currentValue) {
          rowspan++
        } else {
          break
        }
      }
      return {
        rowspan,
        colspan: 1
      }
    }
  }
}
function handleExport() {
  const [startTime, endTime] = queryParams.time || []
  queryParams.startTime = startTime ? startTime : ''
  queryParams.endTime = endTime ? endTime : ''
  const params = {
    ...queryParams
  }
  delete params.time
  proxy.download(
    'operation/statistics/admin/comboSaleInfo/derive',
    params,
    `设备销售详情数据${new Date().getTime()}.xlsx`
  )
}
// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  queryParams.time = [...state.timeRange]
  handleQuery()
}

function onClose() {
  queryRef.value.resetFields()
  queryParams.pageNum = 1
}

function init(row, params) {
  visible.value = true
  title.value = row.machineName
  queryParams.machineId = row.machineId
  queryParams.startTime = params.startTime
  queryParams.endTime = params.endTime
  queryParams.time = [params.startTime, params.endTime]
  state.timeRange = [params.startTime, params.endTime]
  getList()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px;
}
.type {
  margin-bottom: 20px;
}
.btn-group {
  display: flex;
  align-items: center;
}
.el-radio-group {
  margin: 0 10px;
}
</style>
